'use strict';

(function() {
  var root = document.documentElement;

  function setMetaTheme(color) {
    var meta = document.querySelector('meta[name="theme-color"]');
    if (!meta) {
      meta = document.createElement('meta');
      meta.setAttribute('name', 'theme-color');
      document.head.appendChild(meta);
    }
    meta.setAttribute('content', color);
  }

  function applyTheme(theme) {
    if (theme !== 'dark' && theme !== 'light') return;
    root.setAttribute('data-theme', theme);
    root.style.colorScheme = theme;
    try { localStorage.setItem('theme', theme); } catch (e) {}
    setMetaTheme(theme === 'dark' ? '#000000' : '#FFFFFF');
  }

  function detectTheme() {
    var params = new URLSearchParams(location.search);
    var q = params.get('theme');
    if (q === 'dark' || q === 'light') return q;

    var stored = null;
    try { stored = localStorage.getItem('theme'); } catch (e) {}
    if (stored === 'dark' || stored === 'light') return stored;

    var prefersDark = false;
    try { prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; } catch(e) {}
    return prefersDark ? 'dark' : 'light';
  }

  var theme = detectTheme();
  applyTheme(theme);

  window.setTheme = function(t) { applyTheme(t); };
})();
